﻿import axios from 'axios'
import type { AxiosInstance, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios'
import { ElMessage, ElLoading } from 'element-plus'

// 扩展InternalAxiosRequestConfig类型
declare module 'axios' {
  interface InternalAxiosRequestConfig {
    showLoading?: boolean
    showError?: boolean
    loadingInstance?: any
  }
}

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:5052/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加token
    const token = localStorage.getItem('token')
    if (token) {
      if (!config.headers) {
        config.headers = {} as any
      }
      config.headers.Authorization = token 
    }
    
    // 显示加载状态
    if (config.showLoading !== false) {
      config.loadingInstance = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    // 关闭加载状态
    if (response.config.loadingInstance) {
      response.config.loadingInstance.close()
    }
    
    const { data } = response
    
    // 统一处理响应数据
    if (data && typeof data === 'object' && 'code' in data) {
      if (data.code === 200 || data.code === 0) {
        return data
      } else {
        // 业务错误
        if (response.config.showError !== false) {
          ElMessage.error(data.message || '请求失败')
        }
        return Promise.reject(new Error(data.message || '请求失败'))
      }
    }
    
    return data
  },
  (error: AxiosError) => {
    // 关闭加载状态
    if (error.config?.loadingInstance) {
      error.config.loadingInstance.close()
    }
    
    // 处理HTTP错误
    let message = '网络错误，请稍后重试'
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          message = '未授权，请重新登录'
          localStorage.removeItem('token')
          localStorage.removeItem('user')
          window.location.href = '/login'
          break
        case 403:
          message = '拒绝访问'
          break
        case 404:
          message = '请求的资源不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
        default:
          message = (data as any)?.message || '请求失败'
      }
    } else if (error.request) {
      message = '网络连接失败，请检查网络'
    }
    
    if (error.config?.showError !== false) {
      ElMessage.error(message)
    }
    
    return Promise.reject(error)
  }
)

export default api
